package org.raymond.iworks.study.netty.atguigu.netty.inoutbound;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class InOutBoundServer {
    public static void main(String[] args) throws Exception {
        int port = 6666;
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup(2);
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    //.handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addFirst(new LoggingHandler(LogLevel.DEBUG));
                            pipeline.addFirst(new LongToByteEncoder());

                            pipeline.addLast(new ByteToLongDecoder2());
                            pipeline.addLast(new InBoundServerHandler()) // 如果交换顺序,则无法读取到数据
                            ;
                            String result = "";
                        }
                    });
            ChannelFuture future = bootstrap.bind(port).sync();
            future.addListener(f -> {
                if(f.isSuccess()){
                    log.info("监听端口 {} 成功", port);
                }else{
                    log.info("监听端口 {} 失败", port);
                }
            });
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }
}
